import userApi from '@/api/user'

import { setAccessToken, getAccessToken, setRefreshToken, getRefreshToken } from '@/utils/token'

export default {
  state: {
    username: '',
    email: '',
    access_token: getAccessToken(),
    refresh_token: getRefreshToken(),
    access: [],
    hasGetInfo: false
  },
  mutations: {
    setUsername(state, username) {
      state.username = username
    },
    setEmail(state, email) {
      state.email = email
    },
    setAccessToken(state, access_token) {
      state.access_token = access_token
      setAccessToken(access_token)
    },
    setRefreshToken(state, refresh_token) {
      state.refresh_token = refresh_token
      setRefreshToken(refresh_token)
    },
    setHasGetInfo(state, status) {
      state.hasGetInfo = status
    }
  },
  getters: {},
  actions: {
    // 登录
    handleLogin({ commit }, { email, password }) {
      email = email.trim()
      return new Promise((resolve, reject) => {
        userApi
          .login({
            email,
            password
          })
          .then(res => {
            const data = res.data
            commit('setAccessToken', data)
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 退出登录
    handleLogOut({ state, commit }) {
      return new Promise((resolve, reject) => {
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setAccessToken', '')
        commit('setRefreshToken', '')
        resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          userApi
            .getUserInfo()
            .then(res => {
              const data = res.data
              commit('setUsername', data.username)
              commit('setEmail', data.email)
              commit('setHasGetInfo', true)
              resolve(data)
            })
            .catch(err => {
              reject(err)
            })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
